/**
 * Created by tanbingqin on 2020/11/23.
 */
import { messages } from "share/common";
import React from "react";
import { Icon, Button, Row, Col, message, Input, Form, Select, Spin, InputNumber } from "antd";
const Option = Select.Option;
const FormItem = Form.Item;
import Condition from "components/condition";
const If = Condition.If;
import moment from "moment";
import errorMessage from "share/errorMessage";
import travelUtil from "containers/request/travel-request/travelUtil";
import requestUtil from "containers/request/slide/request-util";
import travelService from "containers/request/travel-request/travel.service";
import DatePicker from "components/antd-compatible/date-picker";
const { RangePicker } = DatePicker;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
import iconWarning from "images/travel/icon-warning.png";

class TravelCar extends React.Component {
  state = {
    tabList: [], //用车类型列表
    loading: false,
    typeLoading: false,
    ruleLoading: false,
    didiRules: [], //滴滴用车制度
    typeList: [], //接送机类型列表
    selectRule: null,
    isConsumerErr: false, //行程头的城市是否在对应消费商下支持
    ruleCheckResult: {}, //用车权限校验结果
  };

  keyTypeMap = {
    travel: {
      label: messages("request-1.key469") /*差旅用车*/,
      key: "travel",
    },
    date: {
      label: messages("request-1.key471") /*按日期用车*/,
      key: "date",
    },
    times: {
      label: messages("request-1.key555") /*按次用车*/,
      key: "times",
    },
    carQuick: {
      label: messages("request-1.key472") /*马上用车*/,
      key: "carQuick",
    },
    carPickup: {
      label: messages("request-1.key473") /*接送机／火车*/,
      key: "carPickup",
    },
    aliCar: {
      label: messages("request-1.key923") /*阿里用车*/,
      key: "aliCar",
    },
  };

  carTypeMap = {
    travel: 1,
    date: 3,
    times: 2,
    carQuick: 4,
    carPickup: 5,
    aliCar: 6,
  };

  carTypeMapReverse = {
    1: "travel",
    3: "date",
    2: "times",
    4: "carQuick",
    5: "carPickup",
    6: "aliCar",
  };

  componentDidMount() {
    this.initTabList();
    this.initRules();
    this.initTypeList();
    this.initSelectRule();
  }

  initSelectRule = () => {
    const { field, isEdit } = this.props;
    if (isEdit) {
      let carField = field.showValue ? JSON.parse(field.showValue) : {};
      this.setState({ selectRule: carField.regulation });
    }
  };

  initTabList = () => {
    const { field, isEdit } = this.props;
    let tabList = [];
    if (field && field.fieldConstraint) {
      let typeList = JSON.parse(field.fieldConstraint).typeList || [];
      typeList.forEach((type) => {
        this.keyTypeMap[type] && tabList.push(this.keyTypeMap[type]);
      });
    }
    this.setState({ tabList }, () => {
      !isEdit && this.checkCity(this.state.tabList.length ? this.state.tabList[0].key : undefined);
    });
  };

  checkCity = (carType) => {
    const { itinerary } = this.props;
    let searchTypeMap = {
      travel: "didi",
      date: "didi",
      times: "", //按次用车无需城市校验
      carQuick: "ctrip_car",
      carPickup: "ctrip_carpickup",
      aliCar: "alitrip_car",
    };
    let searchType = carType ? searchTypeMap[carType] : "";
    let country = "all";
    let extraParams = { businessType: "isCar" };

    if (searchType) {
      this.setState({ loading: true });
      if (carType === "travel") {
        Promise.all([
          travelService.isCityInVendor(searchType, itinerary.fromCityCode, country, extraParams),
          travelService.isCityInVendor(searchType, itinerary.toCityCode, country, extraParams),
        ])
          .then((res) => {
            if (res[0].data && res[0].data.alias && res[1].data && res[1].data.alias) {
              this.setState({ isConsumerErr: false });
            } else {
              this.setState({ isConsumerErr: true });
            }
            this.setState({ loading: false });
          })
          .catch((e) => {
            this.setState({ loading: false, isConsumerErr: true });
          });
      } else {
        travelService
          .isCityInVendor(searchType, itinerary.toCityCode, country, extraParams)
          .then((res) => {
            if (res.data && res.data.alias) {
              this.setState({ isConsumerErr: false });
            } else {
              this.setState({ isConsumerErr: true });
            }
            this.setState({ loading: false });
          })
          .catch((e) => {
            this.setState({ loading: false, isConsumerErr: true });
          });
      }
    } else {
      this.setState({ isConsumerErr: false });
    }
  };

  initRules = () => {
    const { applicantOID, isEdit } = this.props;
    this.setState({ loading: true });
    travelService
      .getDiDiRegulation(applicantOID)
      .then((res) => {
        this.setState({ didiRules: res.data, loading: false }, () => {
          !isEdit && this.initDidiRule();
        });
      })
      .catch(() => {
        this.setState({ loading: false });
      });
  };

  initTypeList = () => {
    this.setState({ typeLoading: true });
    travelService
      .getTypeList()
      .then((res) => {
        this.setState({ typeList: res.data, typeLoading: false });
      })
      .catch(() => {
        this.setState({ typeLoading: false });
      });
  };

  initEditValue = (key) => {
    const { field } = this.props;
    let carField = field.showValue ? JSON.parse(field.showValue) : {};
    switch (key) {
      case "approvalType":
        return this.carTypeMapReverse[carField[key] + ""];
      case "regulationId":
        // if (carField.regulation) {
        //   this.setState({ selectRule: carField.regulation });
        // }
        // 以上三行会造成initialValue重复执行死循环，很奇怪
        break;
      case "carDate":
        return [moment(carField.startDate), moment(carField.endDate)];
    }
    return carField[key];
  };

  handleStatusChange = (value, key) => {
    //切换用车类型
    if (key === "carType") {
      this.props.form.resetFields();
      this.setState({ selectRule: null }, () => {
        this.initDidiRule(value);
      });
      this.checkCity(value);
    }
  };

  selectRule = (e, opt) => {
    this.setState(
      {
        selectRule: opt.props["data-rule"],
      },
      this.checkRule
    );
  };

  renderDidiRules = () => {
    const { didiRules } = this.state;
    const { getFieldValue } = this.props.form;
    let carType = getFieldValue("carType");
    if (carType === "travel") {
      return didiRules["businessRegulationList"] ? didiRules["businessRegulationList"] : [];
    }
    if (carType === "date") {
      return didiRules["dateRegulationList"] ? didiRules["dateRegulationList"] : [];
    }
    if (carType === "times") {
      return didiRules["numberRegulationList"] ? didiRules["numberRegulationList"] : [];
    }
    return [];
  };

  //默认选中第一个规则
  initDidiRule = (type) => {
    const { didiRules } = this.state;
    const { getFieldValue } = this.props.form;
    let carType = type || getFieldValue("carType");
    if (carType === "travel" && didiRules["businessRegulationList"] && didiRules["businessRegulationList"].length) {
      this.setState(
        {
          selectRule: didiRules["businessRegulationList"][0],
        },
        this.checkRule
      );
      this.props.form.setFieldsValue({ didiRule: didiRules["businessRegulationList"][0].regulationId });
    }
    if (carType === "date" && didiRules["dateRegulationList"] && didiRules["dateRegulationList"].length) {
      this.setState(
        {
          selectRule: didiRules["dateRegulationList"][0],
        },
        this.checkRule
      );
      this.props.form.setFieldsValue({ didiRule: didiRules["dateRegulationList"][0].regulationId });
    }
    if (carType === "count" && didiRules["numberRegulationList"] && didiRules["numberRegulationList"].length) {
      this.setState(
        {
          selectRule: didiRules["numberRegulationList"][0],
        },
        this.checkRule
      );
      this.props.form.setFieldsValue({ didiRule: didiRules["numberRegulationList"][0].regulationId });
    }
  };

  //校验用车制度的权限，新建带出默认值，切换tab带出默认值，切换制度时都要进行用车制度权限校验
  checkRule = () => {
    const { applicationOID } = this.props;
    const { selectRule } = this.state;
    this.setState({ ruleCheckResult: {} });
    if (applicationOID && selectRule.regulationId) {
      this.setState({ ruleLoading: true });
      travelService
        .checkDiDiRegulation(applicationOID, selectRule.regulationId)
        .then((res) => {
          let ruleCheckResult = {};
          if (res.data && res.data.success) {
            let userNameCheckList = []; //权限有问题的user的name的list
            let userNameStr = "";
            res.data.rows &&
              res.data.rows.userCheckResult.map((user) => {
                if (!user.result) {
                  userNameCheckList.push(user.userName);
                }
              });
            userNameStr = userNameCheckList.join(",");
            let content = messages("request-1.key551", {
              arg1: userNameCheckList.length,
              arg2: selectRule.regulationName,
              arg3: userNameStr,
            }); /*{arg1}人未分配“{arg2}”：{arg3}*/
            if (userNameStr) {
              ruleCheckResult = {
                type: "warning",
                content: (
                  <div className="car-rule-info-block">
                    <img className="icon-warning" src={iconWarning} />
                    <div>
                      {messages("request-1.key553") /*当前出行人中*/}：{content}。
                      {messages("request-1.key554") /*审批通过后将没有用车权限。*/}
                    </div>
                  </div>
                ),
              };
            }
          } else {
            ruleCheckResult = {
              type: "error",
              content: <div>{res.data.message}</div>,
            };
          }
          this.setState({ ruleCheckResult });
        })
        .finally(() => {
          this.setState({ ruleLoading: false });
        });
    }
  };

  //提供给父组件的调用方法 -- start --
  validateItemsValue = () => {
    const { isConsumerErr } = this.state;
    let result = {};
    this.props.form.validateFields((err, values) => {
      if (!err && !isConsumerErr) {
        result = { validateResult: true };
      } else {
        result = { validateResult: false };
      }
    });
    return result;
  };

  getItemValues = () => {
    const { itinerary } = this.props;
    let values = this.props.form.getFieldsValue();
    let resultValues = {
      regulationId: values.didiRule,
      startDate: itinerary.startDate,
      endDate: itinerary.endDate,
      approvalType: this.carTypeMap[values.carType],
      carPickUpType: values.pickupPlan,
      departureCityCode: itinerary.fromCityCode,
      destinationCityCode: itinerary.toCityCode,
      tripTimes: values.useCarNum,
      tripAmount: values.carAmount,
    };
    if (values.carDate) {
      resultValues.startDate = moment(values.carDate[0]).hours(0).minutes(0).seconds(0).utc().format();
      resultValues.endDate = moment(values.carDate[1]).hours(0).minutes(0).seconds(0).utc().format();
    }
    return JSON.stringify(resultValues);
  };
  //提供给父组件的调用方法 -- end --

  render() {
    const {
      tabList,
      loading,
      typeLoading,
      ruleLoading,
      typeList,
      selectRule,
      isConsumerErr,
      ruleCheckResult,
    } = this.state;
    const { formInfo, field, isEdit, itinerary } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    return (
      <div>
        <Spin spinning={loading || typeLoading || ruleLoading}>
          <FormItem {...formItemLayout} label={messages("request-1.key499") /*用车类型*/}>
            {getFieldDecorator("carType", {
              rules: [
                {
                  required: true,
                  message: messages("common.select") /*请选择*/,
                },
              ],
              initialValue: isEdit ? this.initEditValue("approvalType") : tabList.length ? tabList[0].key : undefined,
            })(
              <Select
                placeholder={messages("common.select") /*请选择*/}
                showArrow={true}
                onChange={(value) => this.handleStatusChange(value, "carType")}
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                disabled={field.isReadOnly}
              >
                {tabList.map((option) => {
                  return (
                    <Option key={option.key} value={option.key}>
                      {option.label}
                    </Option>
                  );
                })}
              </Select>
            )}
            <If value={isConsumerErr}>
              <div className="has-error">
                <div className="ant-form-explain">
                  {messages("request-1.key900") /*此用车类型不支持当前行程所选城市*/}
                </div>
              </div>
            </If>
          </FormItem>

          {["travel", "date", "times"].indexOf(getFieldValue("carType")) > -1 && (
            <FormItem {...formItemLayout} label={messages("request-1.key500") /*用车制度*/}>
              {getFieldDecorator("didiRule", {
                rules: [
                  {
                    required: true,
                    message: messages("common.select") /*请选择*/,
                  },
                ],
                initialValue: isEdit ? this.initEditValue("regulationId") : undefined,
              })(
                <Select
                  placeholder={messages("common.select") /*请选择*/}
                  showArrow={true}
                  onSelect={(e, opt) => this.selectRule(e, opt)}
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  disabled={field.isReadOnly}
                >
                  {this.renderDidiRules().map((rule) => {
                    return (
                      <Option data-rule={rule} key={rule.regulationId}>
                        {rule.regulationName}
                      </Option>
                    );
                  })}
                </Select>
              )}
              <If value={ruleCheckResult && ruleCheckResult.type}>
                <If value={ruleCheckResult.type === "warning"}>{ruleCheckResult.content}</If>
                <If value={ruleCheckResult.type === "error"}>
                  <div className="has-error">
                    <div className="ant-form-explain">{ruleCheckResult.content}</div>
                  </div>
                </If>
              </If>
              {selectRule && selectRule.showValue && <div className="show-value-font">{selectRule.showValue}</div>}
            </FormItem>
          )}

          {requestUtil.isShowCarDate(formInfo) && (
            <FormItem {...formItemLayout} label={messages("request-1.key898") /*开始日期-结束日期*/}>
              {getFieldDecorator("carDate", {
                rules: [
                  {
                    required: requestUtil.isCarField(field, getFieldValue("carType"), "startEndDate", "required"),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
                initialValue: isEdit
                  ? this.initEditValue("carDate")
                  : [moment(itinerary.startDate), moment(itinerary.endDate)],
              })(
                <RangePicker
                  allowClear={false}
                  getCalendarContainer={(triggerNode) => triggerNode.parentNode}
                  format="YYYY-MM-DD"
                  placeholder={[messages("common-1.key1217") /*出发日期*/, messages("common-1.key1218") /*返回日期*/]}
                  style={{ width: "66%" }}
                  disabledDate={(current) =>
                    requestUtil.disabledDateByParam(current, itinerary.startDate, itinerary.endDate, true)
                  }
                  disabled={field.isReadOnly}
                />
              )}
            </FormItem>
          )}

          {/*按次用车、马上用车*/}
          {(getFieldValue("carType") === "times" || getFieldValue("carType") === "carQuick") && (
            <div>
              {requestUtil.isCarField(field, getFieldValue("carType"), "useTimes", "show") && (
                <FormItem {...formItemLayout} label={messages("request-1.key503") /*用车次数*/}>
                  {getFieldDecorator("useCarNum", {
                    rules: [
                      {
                        required: requestUtil.isCarField(field, getFieldValue("carType"), "useTimes", "required"),
                        message: messages("common.please.input") /*请输入*/,
                      },
                    ],
                    initialValue: isEdit ? this.initEditValue("tripTimes") : undefined,
                  })(
                    <InputNumber
                      placeholder={messages("request-1.key579") /*请输入temp2*/}
                      precision={0}
                      min={1}
                      max={99}
                      disabled={field.isReadOnly}
                    />
                  )}
                </FormItem>
              )}
            </div>
          )}

          {/*按日期用车、马上用车*/}
          {(getFieldValue("carType") === "date" || getFieldValue("carType") === "carQuick") && (
            <div>
              {requestUtil.isCarField(field, getFieldValue("carType"), "carStandard", "show") && (
                <FormItem {...formItemLayout} label={messages("request-1.key899") /*标准*/}>
                  {getFieldDecorator("carAmount", {
                    rules: [
                      {
                        required: requestUtil.isCarField(field, getFieldValue("carType"), "carStandard", "required"),
                        message: messages("common.please.input") /*请输入*/,
                      },
                    ],
                    initialValue: isEdit ? this.initEditValue("tripAmount") : undefined,
                  })(
                    <InputNumber
                      placeholder={messages("request-1.key579") /*请输入temp2*/}
                      precision={2}
                      max={9999999999}
                      min={0}
                      disabled={field.isReadOnly}
                    />
                  )}
                </FormItem>
              )}
            </div>
          )}

          {/*接送机用车*/}
          {getFieldValue("carType") === "carPickup" && (
            <div>
              <FormItem {...formItemLayout} label={messages("request-1.key507") /*接送类型*/}>
                {getFieldDecorator("pickupPlan", {
                  rules: [
                    {
                      required: true,
                      message: messages("common.select") /*请选择*/,
                    },
                  ],
                  initialValue: isEdit ? this.initEditValue("carPickUpType") : undefined,
                })(
                  <Select
                    allowClear
                    placeholder={messages("common.select") /*请选择*/}
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    disabled={field.isReadOnly}
                  >
                    {typeList.map((type) => (
                      <Option value={type.code} key={type.code}>
                        {type.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </div>
          )}
        </Spin>
      </div>
    );
  }

  static propTypes = {
    field: React.PropTypes.object, //用车主控件
    applicantOID: React.PropTypes.string, //单据申请人
    applicationOID: React.PropTypes.string, //单据oid
    formInfo: React.PropTypes.object, //单据的表单信息
    isEdit: React.PropTypes.bool, //标记是新建还是编辑，初始值的时候逻辑不一样
    itinerary: React.PropTypes.object, //行程头
  };

  static defaultProps = {
    field: {},
    applicantOID: "",
    applicationOID: "",
    formInfo: {},
    isEdit: false,
    itinerary: {},
  };
}

const WrappedTravelCar = Form.create()(TravelCar);
export default WrappedTravelCar;
